package org.xiaoyu.rpc.remoting.transport.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.*;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollServerSocketChannel;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import lombok.extern.slf4j.Slf4j;
import org.xiaoyu.rpc.remoting.RemotingServer;
import org.xiaoyu.rpc.remoting.codec.Codec;
import org.xiaoyu.rpc.remoting.transport.MyDynamicLengthFrameDecoder;
import org.xiaoyu.rpc.remoting.transport.NettyCodecAdapter;
import org.xiaoyu.rpc.remoting.transport.PacketCodecHandler;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * Created By Have
 * 2021/7/5 13:25
 */
@Slf4j
public class RpcNettyServer implements RemotingServer {
    private static final int MAX_WORKER_THREAD = 12;

    private Integer port;

    private final EventLoopGroup bossGroup;
    private final EventLoopGroup workGroup;
    private ServerBootstrap serverBootstrap;
    private Channel channel;
    private static final DefaultEventExecutorGroup executor = new DefaultEventExecutorGroup(Runtime.getRuntime().availableProcessors(), new ThreadFactory() {
        private AtomicInteger aoi = new AtomicInteger();

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "NettyWorkerThread-" + aoi.getAndIncrement());
        }
    });

    public RpcNettyServer() {
        log.info("*********************************************");
        log.info("Epoll Is Available? [{}]", Epoll.isAvailable());
        log.info("*********************************************");

        if (Epoll.isAvailable()) {
            bossGroup = new EpollEventLoopGroup(1);
            workGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2 > MAX_WORKER_THREAD ? MAX_WORKER_THREAD: Runtime.getRuntime().availableProcessors() * 2);

        } else {
            bossGroup = new NioEventLoopGroup(1);
            workGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2 > MAX_WORKER_THREAD ? MAX_WORKER_THREAD: Runtime.getRuntime().availableProcessors() * 2);
        }
        serverBootstrap = new ServerBootstrap();
    }

    public RpcNettyServer(Integer port) {
        this.port = port;
        log.info("*********************************************");
        log.info("Epoll Is Available? [{}]", Epoll.isAvailable());
        log.info("*********************************************");


        if (Epoll.isAvailable()) {
            bossGroup = new EpollEventLoopGroup(1);
            workGroup = new EpollEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2 > MAX_WORKER_THREAD ? MAX_WORKER_THREAD: Runtime.getRuntime().availableProcessors() * 2);

        } else {
            bossGroup = new NioEventLoopGroup(1);
            workGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 2 > MAX_WORKER_THREAD ? MAX_WORKER_THREAD: Runtime.getRuntime().availableProcessors() * 2);
        }
       serverBootstrap = new ServerBootstrap();
    }

    @Override
    public void init(int port) {
        this.port = port;
    }

    @Override
    public void start() {
        try {

            serverBootstrap.group(bossGroup, workGroup)
                    .channel(Epoll.isAvailable()? EpollServerSocketChannel.class: NioServerSocketChannel.class)
//                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
//                    .option(ChannelOption.SO_REUSEADDR, Boolean.TRUE)
//                    .option(ChannelOption.SO_BACKLOG, 256)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
//                    .childOption(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                    .childOption(ChannelOption.TCP_NODELAY, true)
                    .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
//                            pipeline.addLast(PacketCodecHandler.INSTANCE);
//                            pipeline.addLast(ServerHeartbeatHandler.INSTANCE);
//                            pipeline.addLast(RpcIdleHandler.INSTANCE);
//                            pipeline.addLast(NettyServerHandler.INSTANCE);
//                            pipeline.addLast(new MyDynamicLengthFrameDecoder(1024));

                            NettyCodecAdapter adapter = new NettyCodecAdapter(new Codec());
                            pipeline.addLast("encoder", adapter.getEncoder());
                            pipeline.addLast("decoder", adapter.getDecoder());
//                            pipeline.addLast(ServerHeartbeatHandler.INSTANCE);
                            pipeline.addLast(executor, NettyServerHandler.INSTANCE);
                            pipeline.addLast(RpcIdleHandler.INSTANCE);
                        }
                    });
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            channelFuture.syncUninterruptibly();
            channel = channelFuture.channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("服务器启动发生错误:[{}]", e.getMessage());
        } finally {
            bossGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }
    }

    @Override
    public void shutdown() {
        bossGroup.shutdownGracefully().syncUninterruptibly();
        workGroup.shutdownGracefully().syncUninterruptibly();
    }
}
